'use strict';

const authConst = require('../constant/auth-const');
const Service = require('egg').Service;

class UserService extends Service {
    async getAppUserRoleSrv() {
        const { app } = this;

        return await app.model.Role.findOne({
            where: {
                type: authConst.roleType.appRole.value
            },
            attributes: ['id']
        });
    }

    async addUserSrv(userData) {
        const { app, ctx } = this;
        const { username, password, third_id } = userData;

        if (password) {
            userData.password = ctx.helper.encrypt(userData.password);
        }

        const [result, created] = await app.model.User.findCreateFind({
            where: {
                username,
                third_id
            },
            defaults: userData
        });
        console.log('created:', created);

        return created ? result : created;
    }

    async getUserSrv(userData) {
        const { app, ctx } = this;

        if (userData.password) {
            userData.password = ctx.helper.encrypt(userData.password);
        }

        const exclude = ['password'];
        return await app.model.User.findOne({
            where: userData,
            attributes: {exclude}
        });
    }

    async getUserByPasswordSrv(username, password) {
        const { app, ctx } = this;

        if (password) {
            password = ctx.helper.encrypt(password);
        }

        const result = await app.model.User.findOne({
            where: {
                username
            }
        });

        if (result) {
            if (result.password === password) {
                return result;
            } else {
                throw new Error('password miss match');
            }
        } else {
            return null;
        }
    }

    async getUserByIdSrv(userId) {
        const { app } = this;

        return await app.model.User.findOne({
            where: {
                user_id: userId,
                type: authConst.userType.admin.value
            }
        });
    }

    async getUserAllSrv() {
        const { app } = this;

        return await app.model.User.findAll({
            where: {
                type: authConst.userType.admin.value
            }
        });
    }

    async delUserByIdSrv(userId) {
        const { app, ctx } = this;

        try {
            return await app.model.User.destroy({
                where: {
                    id: userId
                }
            });
        } catch (error) {
            ctx.errorResult(error.message);
        }
    }
}

module.exports = UserService;
